<template>
	<el-dropdown split-button>
		<input type="text" v-model="value" style="display:none;" />
		{{dropdownLable}}
		<el-dropdown-menu slot="dropdown">
			<el-tree
				:data="data"
				:default-expand-all="true"
				:expand-on-click-node="false"
				@node-click="handleNode"
				v-bind="$attrs">
			</el-tree>
		</el-dropdown-menu>
	</el-dropdown>
</template>

<script>
	/*
	 *单选下拉树
	 * value 双向绑定属性
	 * data 树形数据
	 * excludeId 要排除的主键
	 * placeholder 默认显示文本
	 * refName 组件ref
	 * 
	 */
	export default {
		inheritAttrs: false,
		props: {
			value: Number,
			data: Array,
			excludeId: {
				type: Number,
				default: 0,
			},
			placeholder: {
				type: String,
				default: '无父级',
			},
			refName: {
				type: String,
				default: 'ref' + new Date().getTime()
			},
		},
		data() {
			return {
				dropdownLable: this.placeholder,
				intiData: this.data,
			}
		},
		methods: {
			handleNode(data) {
				if (this.excludeId === data.id && this.excludeId != 0) {
					this.$message.error('不能选择自身为父级！');
					return false;
				}
				this.dropdownLable = data.title;
				this.$emit('input', data.id);
			},
			//根据Id获得父级名称
			findParentTitle: function (_id, nodes, path) {
				let _this = this;
				if (path === undefined) {
					path = [];
				}
				if (_id == 0) {
					return _this.placeholder;
				}
				for (let i = 0; i < nodes.length; i++) {
					let tmpPath = path.concat();
					tmpPath.push(nodes[i].id);
					if (_id == nodes[i].id) {
						let title = nodes[i].title;
						return title;
					}
					if (nodes[i].children) {
						let findResult = _this.findParentTitle(_id, nodes[i].children, tmpPath);
						if (findResult) {
							return findResult;
						}
					}
				}
			},
		},
		watch: {
			value(newVal) {
				let _this = this;
				if (this.value != 0) {
					_this.dropdownLable = _this.findParentTitle(_this.value, _this.data);
				} else {
					_this.dropdownLable = _this.placeholder;
				}
			}
		}
	}
</script>

<style lang="scss">
</style>